import { Tabs } from 'antd';
import { useState, useEffect, useRef } from 'react';
import GrafanaWrap from '../../Monitor/grafana'
import { useIntl } from 'umi';

const monitorPannelTargetUrlBase = '/grafana/d/hOk70b34k/app-mysql';
const abnormalEventsTargetUrlBase = '/grafana/d/Ub__1x3Vz/app-mysql-events';

/**
 * 封装 useState，使其具有 getState 方法，保证在回调函数中获取到的 state 值是最新的
 * （由于闭包，直接在回调函数中使用state获取到的不是最新值）
 * @param {*} initVal
 * @reference https://www.haorooms.com/post/usegetstate_hooks
 * @returns
 */
const useGetState = (initVal) => {
    const [state, setState] = useState(initVal);
    const ref = useRef(initVal);
    const setStateCopy = (newVal) => {
        ref.current = newVal;
        setState(newVal);
    }
    const getState = () => ref.current;
    return [state, setStateCopy, getState];
}

/**
 * MySQL应用观测
 * @returns 
 */
const AppObservableMysql = (props) => {
    const intl = useIntl();
    const [monitorPannelTargetUrl, setMonitorPannelTargetUrl] = useState(monitorPannelTargetUrlBase);
    const [abnormalEventsTargetUrl, setAbnormalEventsTargetUrl] = useState(abnormalEventsTargetUrlBase);
    const [currentTab, setCurrentTab, getCurrentTab] = useGetState('monitor_panenl');

    useEffect(() => {
        const queryParams = !!props.location?.query ? props.location.query : {};
        console.log(queryParams);
        if ('_currentTab' in queryParams) {
            let _currentTab = queryParams._currentTab;
            if (_currentTab == 'abnormal_events') {
                setCurrentTab('abnormal_events');
            } else {
                setCurrentTab('monitor_panenl');
            }
        }
        // queryParams to query string
        const queryStr = Object.keys(queryParams).map(key => key + '=' + queryParams[key]).join('&').trim();
        if (queryStr.length > 0) {
            setMonitorPannelTargetUrl(monitorPannelTargetUrlBase + `?${queryStr}`);
            setAbnormalEventsTargetUrl(abnormalEventsTargetUrlBase + `?${queryStr}`);
        }
    }, []);

    const monitor_panenl = {
        label: intl.formatMessage({
            id: 'pages.app_observable.monitor_dashboard',
            defaultMessage: 'Monitor Dashboard',
        }),
        key: "monitor_panenl",
        forceRender: true,
        children: (
            <div>
                {
                    currentTab == "monitor_panenl" ?
                        <GrafanaWrap
                            src={monitorPannelTargetUrl}
                            onUrlChange={newUrl => {
                                if (getCurrentTab() == 'monitor_panenl') {
                                    setAbnormalEventsTargetUrl(newUrl.replace(monitorPannelTargetUrlBase, abnormalEventsTargetUrlBase));
                                    if (newUrl.indexOf(abnormalEventsTargetUrlBase) >= 0) {
                                        setCurrentTab('abnormal_events');
                                    }
                                }
                            }}
                            urlChangeInvokeInterval={100}
                        />
                        :
                        <span>monitor_panenl</span>
                }
            </div>
        )
    }

    const abnormal_events = {
        label: intl.formatMessage({
            id: 'pages.app_observable.abnormal_events',
            defaultMessage: 'Abnormal Events',
        }),
        key: "abnormal_events",
        forceRender: true,
        children: (
            <div>
                {
                    currentTab == "abnormal_events" ?
                        <GrafanaWrap
                            src={abnormalEventsTargetUrl}
                            onUrlChange={newUrl => {
                                if (getCurrentTab() == 'abnormal_events') {
                                    setMonitorPannelTargetUrl(newUrl.replace(abnormalEventsTargetUrlBase, monitorPannelTargetUrlBase));
                                    if (newUrl.indexOf(monitorPannelTargetUrlBase) >= 0) {
                                        setCurrentTab('monitor_panenl');
                                    }
                                }
                            }}
                            urlChangeInvokeInterval={100}
                        />
                        :
                        <span>abnormal_events</span>
                }

            </div>
        )
    }
    return (
        <div>
            <Tabs
                activeKey={currentTab}
                tabPosition='left'
                items={[monitor_panenl, abnormal_events]}
                onChange={(key) => {
                    setCurrentTab(key);
                }}
            />
        </div>
    )
};
export default AppObservableMysql;